/* Copyright (C) 
 * 2010 - Insighten  taco [tacoee@gmail.com]
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 */
#include <stdlib.h>
#include <string.h>
#include "fifo.h"

#define min(a,b)	((a)>(b)?(b):(a))

static int is2power(int num)
{
	int j = 1;
	while (num > j) {
		j <<= 1;
	}
	
	return j==num?1:0;
}

struct fifo *fifo_init(int size, int lock_flag)
{
	struct fifo *thiz = NULL;

	if (!is2power(size)) {
		return -1;
	}

	thiz = calloc (sizeof(struct fifo), 1);
	if (thiz != NULL) {
		thiz->data = calloc(sizeof(char)*size, 1);
		if (!thiz->data) {
			free(thiz);
			return NULL;
		}
		thiz->size = size;
		thiz->in = thiz->out = 0;
		thiz->lock_flag = lock_flag;
		if(lock_flag) {
			pthread_mutex_init(&thiz->mutex, NULL);
		}
	}

	return thiz;
}

int fifo_free(struct fifo *thiz)
{
	if (!thiz) {
		return -1;
	}
	if (thiz->data){
		free(thiz->data);
	}
	if (thiz->lock_flag) {
		pthread_mutex_destroy(&thiz->mutex);
	}
	free(thiz);

	return 0;
}

unsigned int fifo_write(struct fifo *thiz, 
		unsigned char *data, unsigned int len)
{
	unsigned int l;

	if(!thiz || !data) {
		return -1;
	}
	len = min(len, thiz->size - thiz->in + thiz->out);

	l = min(len, thiz->size - (thiz->in & (thiz->size - 1)));
	if (thiz->lock_flag) {
		pthread_mutex_lock(&thiz->mutex);
	}
	memcpy(thiz->data + (thiz->in & (thiz->size - 1)), data, l);

	memcpy(thiz->data, data + l, len - l);

	thiz->in += len;
	if (thiz->lock_flag) {
		pthread_mutex_unlock(&thiz->mutex);
	}

	return len;
}

unsigned int fifo_read(struct fifo *thiz,
		unsigned char *data, unsigned int len)
{
	unsigned int l;

	if (!thiz || !data) {
		return -1;
	}

	len = min(len, thiz->in - thiz->out);

	l = min(len, thiz->size - (thiz->out & (thiz->size - 1)));

	memcpy(data, thiz->data + (thiz->out & (thiz->size - 1)), l);

	memcpy(data + l, thiz->data, len - l);

	thiz->out += len;

	return len;
}
